const { ByteQueue } = require('../utils/byteQueue');

class BackendHandler {
    constructor(backendSocket, frontendSocket, ledInterface) {
        this.backendSocket = backendSocket;
        this.frontendSocket = frontendSocket;
        this.ledInterface = ledInterface;
        this.byteQueue = new ByteQueue(100);
    }

    // 处理从LED显示屏接收的数据
    handleData(data) {
        try {
            // 将数据放入队列
            this.byteQueue.put(data);

            // 处理响应命令
            if (this.isResponseCommand(data)) {
                this.handleResponseCommand(data);
                return;
            }

            // 处理队列中的数据
            this.processQueueData();
        } catch (error) {
            console.error('处理LED显示屏数据错误:', error);
            this.closeConnection();
        }
    }

    // 检查是否是响应命令
    isResponseCommand(data) {
        return (
            this.matchBytes(data, this.ledInterface.FeiKongPowerOnReply) ||
            this.matchBytes(data, this.ledInterface.FeiKongPowerOffReply) ||
            this.matchBytes(data, this.ledInterface.FeiKongReplyFlag)
        );
    }

    // 处理响应命令
    handleResponseCommand(data) {
        // 处理开机响应
        if (this.matchBytes(data, this.ledInterface.FeiKongPowerOnReply)) {
            console.log('收到开机响应');
            this.ledInterface.InnerControl = 0;
            this.frontendSocket.write(data);
            return;
        }

        // 处理关机响应
        if (this.matchBytes(data, this.ledInterface.FeiKongPowerOffReply)) {
            console.log('收到关机响应');
            this.ledInterface.InnerControl = 0;
            this.frontendSocket.write(data);
            return;
        }

        // 处理通用响应
        if (this.matchBytes(data, this.ledInterface.FeiKongReplyFlag)) {
            console.log('收到通用响应');
            this.frontendSocket.write(data);
            return;
        }
    }

    // 处理队列中的数据
    async processQueueData() {
        // 获取数据包
        while (this.byteQueue.getSize() > 0) {
            const packet = this.byteQueue.take();
            
            // 检查是否是文本内容
            const content = this.handleTextContent(packet);
            if (content) {
                // 转发到飞控软件
                this.frontendSocket.write(packet);
                continue;
            }

            // 处理其他数据包
            if (!this.ledInterface.FeiKongIsMatch) {
                this.frontendSocket.write(packet);
            }
        }
    }

    // 处理文本内容
    handleTextContent(data) {
        // 检查开始标记
        const startIndex = this.findPattern(data, this.ledInterface.FeiKongContentStart);
        if (startIndex === -1) {
            return null;
        }

        // 检查结束标记
        const endIndex = this.findPattern(data, this.ledInterface.FeiKongContentNext);
        if (endIndex === -1) {
            return null;
        }

        // 提取文本内容
        return data.slice(
            startIndex + this.ledInterface.FeiKongContentStart.length,
            endIndex
        );
    }

    // 字节匹配检查
    matchBytes(data, pattern) {
        if (data.length < pattern.length) {
            return false;
        }

        for (let i = 0; i < pattern.length; i++) {
            if (data[i] !== pattern[i]) {
                return false;
            }
        }
        return true;
    }

    // 查找字节模式
    findPattern(data, pattern) {
        for (let i = 0; i <= data.length - pattern.length; i++) {
            let found = true;
            for (let j = 0; j < pattern.length; j++) {
                if (data[i + j] !== pattern[j]) {
                    found = false;
                    break;
                }
            }
            if (found) {
                return i;
            }
        }
        return -1;
    }

    // 关闭连接
    closeConnection() {
        if (this.backendSocket) {
            this.backendSocket.destroy();
        }
        if (this.frontendSocket) {
            this.frontendSocket.destroy();
        }
    }
}

module.exports = { BackendHandler };
